//
//  HelpPayForViewController.m
//  AllFamily
//
//  Created by chirui on 2018/6/12.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "HelpPayForViewController.h"

@interface HelpPayForViewController (){
    
    NSString * pay_pwdStr;
    NSString * _payType;
}
@property (weak, nonatomic) IBOutlet UITextField *moneyText;
@property (weak, nonatomic) IBOutlet UIButton *wxBtn;
@property (weak, nonatomic) IBOutlet UIButton *zfbBtn;
@property (weak, nonatomic) IBOutlet UIButton *balanceBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@end

@implementation HelpPayForViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"健康值充值");
    
    _payType = @"wxpay";
    _wxBtn.selected = YES;
    
    //微信
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payWxResultOpt:)
                                                 name: WX_NOTIFY_KEY
                                               object:nil];
    
    //支付宝
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ZFBSuccess:)
                                                 name: @"zfb"
                                               object:nil];

    // 支付密码输入框
    self.verifyCodeInputView = [[VerifyCodeInputView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-SH_TopHeight)];
    self.verifyCodeInputView.inputView.delegate = self;
    [self.verifyCodeInputView setHidden:YES];
    [self.view addSubview:self.verifyCodeInputView];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)wxBtnClick:(id)sender {
    _payType = @"wxpay";
    _wxBtn.selected = YES;
    _zfbBtn.selected = NO;
    _balanceBtn.selected = NO;
}
- (IBAction)zfbBtnClick:(id)sender {
    
    _payType = @"alipay";
    _wxBtn.selected = NO;
    _zfbBtn.selected = YES;
    _balanceBtn.selected = NO;
}

- (IBAction)balanceBtnClick:(id)sender {
    
    _payType = @"balance";
    _wxBtn.selected = NO;
    _zfbBtn.selected = NO;
    _balanceBtn.selected = YES;
    
}
- (IBAction)sureBtnClick:(id)sender {
    if (_moneyText.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入金额");
        
        return;
    }
    
    if ([_payType isEqualToString:@"balance"]) {
        
        [self checkPayPasswordSetting];
    }else {
        
        [self topUpBanceRequest];
    }
    
}

- (void)checkPayPasswordSetting {
    
    
    [self.verifyCodeInputView setHidden:NO];
    [self.verifyCodeInputView.inputView.textFieldArray[0] becomeFirstResponder];
}

#pragma mark - 支付密码输入完成回调
- (void)inputFinishedWithText:(NSString *)text {
    // text为用户输入的6位密码
     [self.verifyCodeInputView resignFirstResponder];
    self.verifyCodeInputView.hidden = YES;
    pay_pwdStr = text;
    for(UITextField *textField in self.verifyCodeInputView.inputView.textFieldArray) {
        textField.text = @"";
    }
    
    if (pay_pwdStr.length!=6) {
        [SHJudgeTools MBProgressHUDPromptWith:@"支付密码格式不正确" On:self.view];
        return;
    }else {
        
        [self requestPayForNetFor:self.dataDic[@"id"]]; // 余额支付
    }
    
}

// 余额支付
-(void)requestPayForNetFor:(NSString *)order{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",SERVER_HOST,health_balance_api];
    
    NSDictionary * dic = @{@"pay_password":pay_pwdStr,
                           @"token":USER_DEFAULTGet(@"token"),
                           @"mid":USER_DEFAULTGet(@"mid"),
                           @"h_id":order,
                           @"price":_moneyText.text
                           };
    
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:dic  Success:^(id responseObject) {
        
        if ([responseObject[@"code"] intValue]==200) {
            
            UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alerte show];
            
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        NSLog(@"ERROR ==%@",error);
        SHuiMBhudTextNetError;
    }];
}

-(void)topUpBanceRequest {
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"h_id":self.dataDic[@"id"],
                           @"pay_type":_payType,
                           @"price":_moneyText.text
                           
                           };
    SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:RequestUrlStr(Health_Recharge_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if ([responseObject[@"code"] intValue]==200) {
            
            if ([_payType isEqualToString:@"wxpay"]) {
                
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [responseObject[@"datas"][@"Appparam"] objectForKey:@"appid"];
                req.partnerId           = [responseObject[@"datas"][@"Appparam"] objectForKey:@"partnerid"];
                req.prepayId            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"prepayid"];
                req.nonceStr            = [responseObject[@"datas"][@"Appparam"] objectForKey:@"noncestr"];
                req.timeStamp           = [[responseObject[@"datas"][@"Appparam"] objectForKey:@"timestamp"] intValue];
                req.package             = [responseObject[@"datas"][@"Appparam"] objectForKey:@"packages"];
                req.sign                = [responseObject[@"datas"][@"Appparam"] objectForKey:@"sign"];
                
                [WXApi sendReq:req];
                
            }else {
                
                NSString *appScheme = @"AllFamily";
                
                [[AlipaySDK defaultService] payOrder:responseObject[@"datas"][@"pay_string"]  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"reslut = %@",resultDic);
                    
                }];
            }
        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
    
}


//微信支付完成通知
-(void)payWxResultOpt:(NSNotification *)notification
{
    PayResp *response=(PayResp*)notification.object;
    
    if (response.errCode == WXSuccess)
    {
        
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];
        
    }
    else
    {
        UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付失败了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerte show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
 
        if (buttonIndex == 0) {
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
   
}
-(void)ZFBSuccess:(NSNotification *)notification {
    
    UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"支付成功了~~！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alerte show];
}

-(void)dealloc{
    
    //第一种方法.这里可以移除该控制器下的所有通知
    
    NSLog(@"移除了所有的通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}



@end
